package com.desay.pangoo.itmt.repository.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @Description： 逻辑表达式
 * 
 * @author shouyi.huang@desay-svautomotive.com on 2019年7月23日下午8:35:34
 * @Modified By： [] on [] for [修改说明]
 *
 */
public class LogicalExpression implements ExpandCriterion {
    /** 逻辑表达式中包含的表达式 */
    private ExpandCriterion[] criterion;
    /** 计算符 */
    private Operator operator;

    public LogicalExpression(ExpandCriterion[] criterions, Operator operator) {
        this.criterion = criterions;
        this.operator = operator;
    }

    @Override
    public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        List<Predicate> predicates = new ArrayList<>();
        for (int i = 0; i < this.criterion.length; i++) {
            if (null != this.criterion[i]) {
                predicates.add(this.criterion[i].toPredicate(root, query, builder));
            }
        }
        switch (operator) {
        case OR:
            return builder.or(predicates.toArray(new Predicate[predicates.size()]));
        case AND:
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        default:
            return null;
        }
    }
}
